package com.ieasy.basic.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class CookieKit {
	protected static Logger logger = LoggerFactory.getLogger(CookieKit.class);
	
	/**
	 * 写Cookie
	 * @param response
	 * @param cookieParams
	 * @param maxAge 存活时间（60 * 60 * 24 * 365 * 2） 两年
	 * @param path cookie路径 /fast
	 */
	public static final void addCookies(HttpServletResponse response, Map<String, String> cookieParams, int maxAge, String path) {
		if (cookieParams == null || cookieParams.size() == 0)
			return;
		Set<String> keySet = cookieParams.keySet();
		for (String key : keySet) {
			Cookie cookie = new Cookie(key, cookieParams.get(key));
			cookie.setMaxAge(maxAge);
			if(null == path) {
				cookie.setPath("/");
			} else {
				cookie.setPath(path);
			}
			response.addCookie(cookie);
		}
	}
	public static final void addCookies(HttpServletResponse response, Map<String, String> cookieParams, int maxAge) {
		addCookies(response, cookieParams, maxAge, null);
	}
	
	
	/**
	 * 读取Cookie
	 * @param request
	 * @return
	 */
	public static final Cookie[] getCookies(HttpServletRequest request) {
		return request.getCookies();
	}
	public static final Cookie getCookie(HttpServletRequest request, String cookieName) {
		Cookie[] cookies = getCookies(request) ;
		if(null != cookies) {
			for (Cookie cookie : cookies) {
				if(cookie.getName().equals(cookieName)) {
					return cookie;
				}
			}
		}
		return null;
	}
	public static final String getCookieValue(HttpServletRequest request, String cookieName) {
		Cookie[] cookies = getCookies(request) ;
		if(null != cookies) {
			for (Cookie cookie : cookies) {
				if(cookie.getName().equals(cookieName)) {
					return cookie.getValue();
				}
			}
		}
		return null;
	}
	

	/**
	 * 删除所有的cookies
	 * 
	 * @param request
	 * @param response
	 */
	public static final void clearAllCookies(HttpServletRequest request, HttpServletResponse response) {
		Cookie[] cookies = request.getCookies();
		if (cookies == null || cookies.length == 0)
			return;
		Map<String, String> cookiesMap = new HashMap<String, String>();
		for (Cookie cookie : cookies) {
			cookiesMap.put(cookie.getName(), "");
		}
		addCookies(response, cookiesMap, 0);
	}
	
	/**
	 * 删除cookies
	 * 
	 * @param request
	 * @param response
	 */
	public static final void clearCookies(HttpServletRequest request, HttpServletResponse response, String cookieName) {
		Cookie cookie = getCookie(request, cookieName) ;
		if(null != cookie) {
			logger.debug("删除Cookie：" + cookieName);
			cookie.setValue(null);
			cookie.setMaxAge(0);
			cookie.setPath("/");
			response.addCookie(cookie);
		}
	}
	
	public static void main(String[] args) throws UnsupportedEncodingException {
		String aa = "cookieValueWithMd5";
		String c = new String(Base64.encodeBase64URLSafeString(aa.getBytes()));
		System.out.println(c);
		
		String cc = new String(Base64.decodeBase64(c),"utf-8");
		System.out.println(cc);
		
		System.out.println("===========================");
		String u = "admin";
		String p = "12345";
		
		//MD5加密用户详细信息
        String cookieValueWithMd5 =getMD5(u+":"+p);
        //将要被保存的完整的Cookie值
        String cookieValue = u + ":" + cookieValueWithMd5;
        //再一次对Cookie的值进行BASE64编码
        
        System.out.println("cookieValueWithMd5："+cookieValueWithMd5);

        String cookieValueBase64 = new String(Base64.encodeBase64URLSafeString(cookieValue.getBytes()));
        System.out.println("cookieValueBase64："+cookieValueBase64+"="+cookieValueBase64.length());
        
        System.out.println("========================"+Base64.decodeBase64("cc"));
        String cookieValueAfterDecode = new String (Base64.decodeBase64(cookieValueBase64),"utf-8");
        System.out.println(cookieValueAfterDecode+"___"+cookieValueAfterDecode.length());
		
	}

	public static String getMD5(String value) {
		String result = null;
		try {
			byte[] valueByte = value.getBytes();
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(valueByte);
			result = toHex(md.digest());
		} catch (NoSuchAlgorithmException e2) {
			e2.printStackTrace();
		}
		return result;
	}

	// 将传递进来的字节数组转换成十六进制的字符串形式并返回
	private static String toHex(byte[] buffer) {
		StringBuffer sb = new StringBuffer(buffer.length * 2);
		for (int i = 0; i < buffer.length; i++) {
			sb.append(Character.forDigit((buffer[i] & 0xf0) >> 4, 16));
			sb.append(Character.forDigit(buffer[i] & 0x0f, 16));
		}
		return sb.toString();
	}

}
